package com.wyh.utils.feemanagementutils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Component
public class SampleUtil {
    @Value("${ALIBABA_CLOUD_ACCESS_KEY_ID}")
    private String accessKeyId;
    @Value("${ALIBABA_CLOUD_ACCESS_KEY_SECRET}")
    private String accessKeySecret;
    @Value("${TEMPLATE_CODE}")
    private String templateCode;
    @Value("${SIGN_NAME}")
    private String signName;

    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public SendSmsResponse sendSms(String[] phoneNumbers, String code) throws Exception {
        Client client = SampleUtil.createClient(accessKeyId, accessKeySecret);

        List<String> validPhoneNumbers = new ArrayList<>();
        List<String> invalidPhoneNumbers = new ArrayList<>();

        for (String phoneNumber : phoneNumbers) {
            if (isValidPhoneNumber(phoneNumber)) {
                validPhoneNumbers.add(phoneNumber);
            } else {
                invalidPhoneNumbers.add(phoneNumber);
            }
        }

        if (validPhoneNumbers.isEmpty()) {
            throw new Exception("所有的电话号码都无效: " + invalidPhoneNumbers);
        }

        String phoneNumbersStr = String.join(",", validPhoneNumbers);

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phoneNumbersStr)
                .setTemplateParam("{\"code\":\"" + code + "\"}");

        RuntimeOptions runtime = new RuntimeOptions();
        SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);

        if (!invalidPhoneNumbers.isEmpty()) {
            System.out.println("以下电话号码无效: " + invalidPhoneNumbers);
        }

        return sendSmsResponse;
    }

    private boolean isValidPhoneNumber(String phoneNumber) {
        return PHONE_PATTERN.matcher(phoneNumber).matches();
    }
}
